<template>
  <Page>
    <div class="example-app-management">
      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-form">
          <Space>
            <Input
              v-model:value="searchParams.name"
              placeholder="请输入应用名称"
              style="width: 200px"
              @press-enter="handleSearch"
            />
            <Input
              v-model:value="searchParams.code"
              placeholder="请输入应用编码"
              style="width: 200px"
              @press-enter="handleSearch"
            />
            <Select
              v-model:value="searchParams.is_active"
              placeholder="请选择状态"
              style="width: 120px"
              allow-clear
            >
              <SelectOption value="true">启用</SelectOption>
              <SelectOption value="false">禁用</SelectOption>
            </Select>
            <Button type="primary" @click="handleSearch">搜索</Button>
            <Button @click="handleReset">重置</Button>
          </Space>
        </div>
        <div class="action-buttons">
          <Space>
            <Button type="primary" @click="handleAdd">新增应用</Button>
            <Button @click="handleRefresh">刷新</Button>
            <Button 
              :disabled="selectedRowKeys.length === 0"
              danger
              @click="handleBatchDelete"
            >
              批量删除
            </Button>
          </Space>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <Table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          :row-selection="rowSelection"
          row-key="id"
          @change="handleTableChange"
        />
      </div>

      <!-- 表单弹窗 -->
      <Modal
        v-model:open="formVisible"
        :title="formTitle"
        width="800px"
        :footer="null"
        destroy-on-close
      >
        <ExampleAppForm
          v-model:visible="formVisible"
          :data="currentRecord"
          :mode="formMode"
          @success="handleFormSuccess"
        />
      </Modal>

      <!-- 详情弹窗 -->
      <Modal
        v-model:open="detailVisible"
        title="应用详情"
        width="800px"
        :footer="null"
        destroy-on-close
      >
        <ExampleAppDetail
          v-if="detailVisible"
          :data="currentRecord"
        />
      </Modal>
    </div>
  </Page>
</template>

<script setup lang="ts">
import { computed, h, onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { 
  Button, 
  Input, 
  message, 
  Modal, 
  Select, 
  SelectOption, 
  Space, 
  Table, 
  Tag 
} from 'ant-design-vue';

import { 
  exampleAppApi, 
  type ExampleAppItem, 
  type ExampleAppListParams 
} from '#/api/example-app';

import ExampleAppDetail from './components/ExampleAppDetail.vue';
import ExampleAppForm from './components/ExampleAppForm.vue';

defineOptions({
  name: 'ExampleAppManagement',
});

// 响应式数据
const loading = ref(false);
const dataSource = ref<ExampleAppItem[]>([]);
const formVisible = ref(false);
const detailVisible = ref(false);
const formMode = ref<'create' | 'edit'>('create');
const currentRecord = ref<ExampleAppItem | null>(null);
const selectedRowKeys = ref<string[]>([]);

// 搜索参数
const searchParams = reactive({
  name: '',
  code: '',
  is_active: undefined as string | undefined,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: (string | number)[]) => {
    selectedRowKeys.value = keys.map(key => String(key));
  },
}));

// 表格列配置
const columns = [
  {
    title: '应用名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
    ellipsis: true,
  },
  {
    title: '应用编码',
    dataIndex: 'code',
    key: 'code',
    width: 120,
  },
  {
    title: '域名',
    dataIndex: 'domain',
    key: 'domain',
    width: 180,
    ellipsis: true,
    customRender: ({ text }: { text: string }) => text || '-',
  },
  {
    title: '状态',
    dataIndex: 'is_active',
    key: 'is_active',
    width: 100,
    align: 'center' as const,
    customRender: ({ record }: { record: ExampleAppItem }) => {
      return h(
        Tag,
        {
          color: record.is_active ? 'green' : 'red',
        },
        () => (record.is_active ? '启用' : '禁用')
      );
    },
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180,
    customRender: ({ text }: { text: string }) => {
      return new Date(text).toLocaleString();
    },
  },
  {
    title: '更新时间',
    dataIndex: 'updated_at',
    key: 'updated_at',
    width: 180,
    customRender: ({ text }: { text: string }) => {
      return new Date(text).toLocaleString();
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
    customRender: ({ record }: { record: ExampleAppItem }) => {
      return h(Space, {}, () => [
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleView(record),
          },
          () => '查看'
        ),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            onClick: () => handleEdit(record),
          },
          () => '编辑'
        ),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            danger: !record.is_active,
            onClick: () => handleToggleStatus(record),
          },
          () => (record.is_active ? '禁用' : '启用')
        ),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            danger: true,
            onClick: () => handleDelete(record),
          },
          () => '删除'
        ),
      ]);
    },
  },
];

// 计算属性
const formTitle = computed(() => {
  return formMode.value === 'create' ? '新增应用' : '编辑应用';
});

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const params: ExampleAppListParams = {
      page: pagination.current,
      size: pagination.pageSize,
      name: searchParams.name || undefined,
      code: searchParams.code || undefined,
      is_active: searchParams.is_active === 'true' ? true : searchParams.is_active === 'false' ? false : undefined,
    };
    
    const response = await exampleAppApi.getList(params);
    dataSource.value = response.items;
    pagination.total = response.total;
  } catch (error) {
    message.error('获取数据失败');
    console.error('获取应用列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索操作
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

const handleReset = () => {
  searchParams.name = '';
  searchParams.code = '';
  searchParams.is_active = undefined;
  pagination.current = 1;
  fetchData();
};

// 表格操作方法
const handleAdd = () => {
  formMode.value = 'create';
  currentRecord.value = null;
  formVisible.value = true;
};

const handleEdit = (record: ExampleAppItem) => {
  formMode.value = 'edit';
  currentRecord.value = record;
  formVisible.value = true;
};

const handleView = (record: ExampleAppItem) => {
  currentRecord.value = record;
  detailVisible.value = true;
};

const handleDelete = async (record: ExampleAppItem) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除应用 "${record.name}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await exampleAppApi.delete(record.id);
        message.success('删除成功');
        fetchData();
      } catch (error) {
        message.error('删除失败');
        console.error('删除应用失败:', error);
      }
    },
  });
};

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的数据');
    return;
  }

  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个应用吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await exampleAppApi.batchDelete(selectedRowKeys.value);
        message.success('批量删除成功');
        selectedRowKeys.value = [];
        fetchData();
      } catch (error) {
        message.error('批量删除失败');
        console.error('批量删除应用失败:', error);
      }
    },
  });
};

const handleToggleStatus = async (record: ExampleAppItem) => {
  try {
    await exampleAppApi.toggleStatus(record.id, !record.is_active);
    message.success('状态更新成功');
    fetchData();
  } catch (error) {
    message.error('状态更新失败');
    console.error('更新状态失败:', error);
  }
};

const handleRefresh = () => {
  fetchData();
};

const handleTableChange = (paginationInfo: any) => {
  pagination.current = paginationInfo.current;
  pagination.pageSize = paginationInfo.pageSize;
  fetchData();
};

// 表单操作
const handleFormSuccess = () => {
  formVisible.value = false;
  fetchData();
};

const handleFormCancel = () => {
  formVisible.value = false;
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.example-app-management {
  padding: 16px;
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding: 16px;
  background: white;
  border-radius: 6px;
}

.search-form {
  flex: 1;
}

.action-buttons {
  margin-left: 16px;
}

.table-section {
  background: white;
  border-radius: 6px;
  padding: 16px;
}
</style>